package com.yqg.protection.controller.dataHandler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSON;
import com.yqg.protection.controller.vo.FireCockVo;
import com.yqg.protection.entity.*;
import com.yqg.protection.service.*;
import com.yqg.protection.utils.DataSaver;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

/**
 * projectName:xf-service
 * author:zxf
 * time:2025/8/30 17:17
 * description:
 */
@Component
public class FireCockDataHandler {

    @Resource
    protected DataSaver dataSaver;

    @Resource
    private IEquipmentInputStoreService equipmentInputStoreService;

    @Resource
    private ICurrentFireCockService currentFireCockService;

    @Resource
    private IHistoryFireCockService historyFireCockService;

    @Resource
    private IWarnFireCockService warnFireCockService;

    @Resource
    private IWarnRecordService warnRecordService;

    @Resource
    ProtocolUtil protocolUtil;

    public void saveFireCockData(FireCockVo fireCockVo) {
        // 1. 打印接收到的消息
        System.out.println("收到设备消息: " + JSON.toJSONString(fireCockVo));
        EquipmentInputStore equipmentInputStore = protocolUtil.getEquipmentInputStore(fireCockVo.getDeviceId());
        String sendTime = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date(fireCockVo.getTimestamp()));
        // 2. 保存日志文件
        dataSaver.saveDataToFileAsync(JSON.toJSONString(fireCockVo), sendTime, fireCockVo.getDeviceId());
        if (equipmentInputStore != null) {
            String explanation = "";
            CurrentFireCock currentFireCock = new CurrentFireCock();
            currentFireCock.setEquipmentInputStoreId(equipmentInputStore.getId());
            currentFireCock.setUpPacketSn(fireCockVo.getUpPacketSN());
            currentFireCock.setSendTime(LocalDateTimeUtil.of(fireCockVo.getTimestamp()));
            currentFireCock.setDeviceType(fireCockVo.getDeviceType());
            currentFireCock.setProductId(fireCockVo.getProductId());
            currentFireCock.setDeviceId(fireCockVo.getDeviceId());
            currentFireCock.setProtocol(fireCockVo.getProtocol());
            currentFireCock.setMessageType(fireCockVo.getMessageType());
            currentFireCock.setAssocAssetId(fireCockVo.getAssocAssetId());
            currentFireCock.setTenantId(fireCockVo.getTenantId());
            currentFireCock.setImsi(fireCockVo.getIMSI());
            currentFireCock.setTopic(fireCockVo.getTopic());
            currentFireCock.setUpDataSn(fireCockVo.getUpDataSN());
            currentFireCock.setServiceId(fireCockVo.getServiceId());
            Map<String, Object> payload = fireCockVo.getPayload();
            if (fireCockVo.getServiceId().equals("signal_report")) {
                currentFireCock.setPci((Integer) payload.get("pci"));
                currentFireCock.setRsrp((Integer) payload.get("rsrp"));
                currentFireCock.setCellId((Integer) payload.get("cell_id"));
                currentFireCock.setSinr((Integer) payload.get("sinr"));
                currentFireCock.setEcl((Integer) payload.get("ecl"));
                explanation = "上传智能消火栓位置数据";
            } else if (fireCockVo.getServiceId().equals("info_report")) {
                currentFireCock.setIccid((String) payload.get("ICCID"));
                currentFireCock.setImsi((String) payload.get("IMSI"));
                currentFireCock.setLocation((String) payload.get("location"));
                currentFireCock.setPowerType((Integer) payload.get("power_type"));
                currentFireCock.setDevType((Integer) payload.get("dev_type"));
                currentFireCock.setVersion((String) payload.get("version"));
                currentFireCock.setDevModel((Integer) payload.get("dev_model"));
                explanation = "上传智能消火栓基本信息数据";
            } else if (fireCockVo.getServiceId().equals("param_report")) {
                currentFireCock.setSendInterval((Integer) payload.get("send_interval"));
                currentFireCock.setSelfCheckDays((Integer) payload.get("self_check_days"));
                currentFireCock.setSampInterval((Integer) payload.get("samp_interval"));
                currentFireCock.setAlarmsTh((String) payload.get("alarms_th"));
                currentFireCock.setFeaturesBits((Integer) payload.get("features_bits"));
                currentFireCock.setNetwork((String) payload.get("network"));
                explanation = "上传智能消火栓参数数据";
            } else if (fireCockVo.getServiceId().equals("sensor_dat_report")) {
                currentFireCock.setCsq((Integer) payload.get("CSQ"));
                currentFireCock.setAlarmsDat((String) payload.get("alarms_dat"));
                currentFireCock.setAlarm((Integer) payload.get("alarm"));
                currentFireCock.setSensorDat((String) payload.get("sensor_dat"));
                currentFireCock.setDevType((Integer) payload.get("dev_type"));
                currentFireCock.setSampTime((String) payload.get("samp_time"));
                currentFireCock.setDevModel((Integer) payload.get("dev_model"));
                currentFireCock.setBatLevel((Integer) payload.get("bat_level"));
                WarnFireCock warnFireCock = new WarnFireCock();
                BeanUtil.copyProperties(currentFireCock, warnFireCock, true);
                warnFireCockService.save(warnFireCock);
                WarnRecord warnRecord = new WarnRecord();
                warnRecord.setEquipmentInputStoreId(equipmentInputStore.getId());
                warnRecord.setWarnStateNum("1");
                warnRecord.setWarnTypeNum(0);
                warnRecord.setIsDeal(0);
                warnRecord.setIsMisinformation("0");
                warnRecord.setTeleNotification("1");
                warnRecord.setFaultReport("0");
                warnRecord.setFieldSurvey("0");
                warnRecord.setEliminHidDang("0");
                warnRecord.setCreateTime(LocalDateTime.now());
                warnRecord.setWarnTime(sendTime);
                warnRecord.setWarnAddr(equipmentInputStore.getAddress());
                warnRecord.setIsDelete(0);
                warnRecordService.save(warnRecord);
                //报警推送
                ArrayList<WarnRecord> warnRecords = new ArrayList<>();
                warnRecords.add(warnRecord);
                protocolUtil.sendWarnNotice(equipmentInputStore, warnRecords);
                explanation = "上传智能消火栓报警数据";
                equipmentInputStore.setState("1");
            } else if (fireCockVo.getServiceId().equals("emcy_evt_report")) {
                currentFireCock.setEvent((Integer) payload.get("event"));
                explanation = "上传智能消火栓事件数据";
            }
            if (currentFireCock.getImsi() != null && !currentFireCock.getImsi().equals("") && (equipmentInputStore.getSimId() == null || equipmentInputStore.getSimId().equals(""))) {
                equipmentInputStore.setUpdateTime(sendTime);
                equipmentInputStore.setSimId(currentFireCock.getImsi());
            }
            equipmentInputStoreService.saveOrUpdate(equipmentInputStore);
            currentFireCockService.saveOrUpdate(currentFireCock);
            HistoryFireCock historyFireCock = new HistoryFireCock();
            BeanUtil.copyProperties(currentFireCock, historyFireCock, true);
            historyFireCockService.save(historyFireCock);
            protocolUtil.saveFireSysData(fireCockVo.getDeviceId(), explanation, sendTime);
            protocolUtil.updateTemporaryData(fireCockVo.getDeviceId(), sendTime);
        }
    }
}
